package com.lingyue.commons.encrypt;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * Created by IntelliJ IDEA.
 *
 * @Description: TODO
 * @Author: BaiJinhua
 * @Date: 2019/11/26 23:53
 * @See: com.lingyue.common.tools
 * @Version: 1.0
 * Copyright: Copyright (c) 2019
 */
public class AESUtil {

    /**
     *  AES 加/解密密钥
     */
    private static final String SECRET_KEY="8iP6B5ou7eFvphyg";

    /**
     * AES加密
     * @param content
     * @return
     */
    public static String encrypt(String content){
        try {
            SecretKey key=new SecretKeySpec(SECRET_KEY.getBytes("UTF-8"), "AES");
            Cipher cipher=Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return new String(Base64.getEncoder().encode(cipher.doFinal(content.getBytes("utf-8"))));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return content;
    }

    /**
     * AES解密
     * @param content
     * @return
     */
    public static String decrypt(String content){
        try {
            SecretKey key=new SecretKeySpec(SECRET_KEY.getBytes("UTF-8"), "AES");
            Cipher cipher=Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key);
            return new String(cipher.doFinal(Base64.getDecoder().decode(content)),"utf-8");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }


    public static void main(String[] args) {
        String mobile = "85161448132829";
        System.out.println(encrypt(mobile));
        String decrypt = decrypt("sZRg71rxa6SCT7Mc+9UNCw==");
        System.out.println(decrypt);
    }
}
